package org.gikolet.ch2.android.widget;

import org.gikolet.util.ProgressMonitor;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;

public class DialogProgressMonitor implements ProgressMonitor {

	private Message INIT_MSG = new Message();
	private Message DONE_MSG = new Message();
	private Message CANCEL_MSG = new Message();

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			init(msg);
		};
	};

	private OnCancelListener cancelListener = new OnCancelListener() {
		public void onCancel(DialogInterface dialog) {
			cancel();
		}
	};

	private Context context;
	private String title;
	private ProgressDialog progressDialog;
	private int allWork;
	private boolean cancel = false;
	private boolean allWorkUnknown = false;
	private String taskName;

	public DialogProgressMonitor(Context context, String title) {
		this.context = context;
		this.title = title;
	}

	private void init(Message msg) {
		if (msg == INIT_MSG) {
			this.progressDialog = new ProgressDialog(this.context);

			this.progressDialog.setTitle(this.title);
			this.progressDialog
					.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			this.progressDialog.setCancelable(true);
			this.progressDialog.setMax(this.allWork);
			this.progressDialog.setIndeterminate(this.allWorkUnknown);
			this.progressDialog.setOnCancelListener(this.cancelListener);
			this.progressDialog.setMessage(this.taskName);

			this.cancel = false;

			this.progressDialog.show();

		} else if (msg == DONE_MSG) {
			if (this.progressDialog != null) {
				this.progressDialog.dismiss();
			}

		} else if (msg == CANCEL_MSG) {
			this.cancel = true;
		}
	}

	public void setOnCancelListener(OnCancelListener l) {
		this.progressDialog.setOnCancelListener(l);
	}

	public void beginTask(String name, int allWork) {
		if (allWork < 0) {
			this.allWork = 1;
			this.allWorkUnknown = true;

		} else {
			this.allWork = allWork;
			this.allWorkUnknown = false;
		}

		this.taskName = name;

		this.handler.sendMessage(INIT_MSG);

	}

	public void done() {
		this.handler.sendMessage(DONE_MSG);
	}

	public void cancel() {
		this.handler.sendMessage(CANCEL_MSG);
	}

	public boolean isCancelled() {
		return this.cancel;
	}

	public void subTask(String name) {
	}

	public void worked(int work) {
		if (!this.allWorkUnknown) {
			this.progressDialog.setProgress(work);
		}
	}
}
